#!/usr/bin/env bash
# Copyright (c) 2016 Presto Labs Pte. Ltd.
# Author: leon

set -e

SCRIPT_REL_DIR="deploy"
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DEPLOY_REL_DIR=".."
DEPLOY_DIR=$(realpath "${SCRIPT_DIR}/${DEPLOY_REL_DIR}/")

# Changes working directory to the deployed directory.
cd "${DEPLOY_DIR}"

# Gets deploy profile.
source "${SCRIPT_REL_DIR}/profile"

# Removes cron entry
if [ -f "${SCRIPT_DIR}/cron_profile" ]; then
  "${SCRIPT_DIR}/cron_tool" delsection \
    "${DEPLOY_NAME}" \
    "${SCRIPT_DIR}/cron_profile"
fi

# Removes symlink at ${RECENT_DIR}.
RECENT_DIR=${RECENT_DIR:=${HOME}/recent}
TARGET="${RECENT_DIR}/${PACKAGE_NAME}"
if [ -L "${TARGET}" ]; then
  CUR_LINK=$(readlink -f "${TARGET}")
  if [ $(realpath "${CUR_LINK}") == $(realpath "${DEPLOY_DIR}") ]; then
    unlink "${TARGET}"
  fi
fi

# Leaves footprint.
if [ -f "BOOTSTRAPPED" ]; then
  rm "BOOTSTRAPPED"
fi
touch "RETIRED"
